package com.yisu.expressway.service_district;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;

import butterknife.Bind;

public class MapActivity extends BaseActivity {

    @Bind(R.id.bd_map_view)
    protected MapView mMapView;

    private final static String TARGET_LONGITUDE = "target_longitude";
    private final static String TARGET_LATITUDE = "target_latitude";
    private final static String TARGET_NAME = "target_name";
    private final static String ROUTE_START = "route_start";
    private final static String ROUTE_END = "route_end";
    private final static String MAP_TYPE = "map_type";

    public final static int MAP_TYPE_LOCATION = 0;
    public final static int MAP_TYPE_TRAFFIC = 1;
    public final static int MAP_TYPE_ROUTE = 2;

    private BaiduMap mBaiduMap;
    private String mTargetName;
    private int mMapType = MAP_TYPE_LOCATION;
    private double mTargetLongitude;
    private double mTargetLatitude;
    private String mRouteStart;
    private String mRouteEnd;
    // route plan search relative
    private RoutePlanSearch mSearch = null;
    private OnGetRoutePlanResultListener mOnGetRoutePlanResultListener = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        mBaiduMap = mMapView.getMap();
        init();
    }

    private void init() {
        parseIntent(getIntent());
        initMapView();
        if (mMapType == MAP_TYPE_ROUTE) {
            initRoutePlan();
            startSearch();
        }
    }

    private void parseIntent(Intent intent) {
        if (intent != null) {
            mTargetName = intent.getStringExtra(TARGET_NAME);
            mMapType = intent.getIntExtra(MAP_TYPE, MAP_TYPE_LOCATION);
            mTargetLongitude = intent.getDoubleExtra(TARGET_LONGITUDE, -1);
            mTargetLatitude = intent.getDoubleExtra(TARGET_LATITUDE, -1);
            mRouteStart = intent.getStringExtra(ROUTE_START);
            mRouteEnd = intent.getStringExtra(ROUTE_END);
        }
    }

    private void initRoutePlan() {
        mSearch = RoutePlanSearch.newInstance();
        mOnGetRoutePlanResultListener = new OnGetRoutePlanResultListener() {

            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(MapActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    // result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    if (result.getRouteLines().size() >= 1) {
                        DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
                        overlay.setData(result.getRouteLines().get(0));
                        overlay.addToMap();
                        overlay.zoomToSpan();

                    } else {
                        Log.d("route result", "结果数<0");
                        return;
                    }

                }
            }


            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }

        };
        mSearch.setOnGetRoutePlanResultListener(mOnGetRoutePlanResultListener);
    }

    private void startSearch() {
        PlanNode stNode = PlanNode.withCityNameAndPlaceName(mRouteStart, mRouteStart);
        PlanNode enNode = PlanNode.withCityNameAndPlaceName(mRouteEnd, mRouteEnd);
        mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
    }

    public static void launchRoutePlan(Activity context, double longitude, double latitude, String startName, String endName) {
        launch(context, longitude, latitude, context.getResources().getString(R.string.route_plan_search), startName, endName, MAP_TYPE_ROUTE);
    }

    public static void launchLocation(Activity context, double longitude, double latitude, String targetName) {
        launch(context, longitude, latitude, targetName, "", "", MAP_TYPE_ROUTE);
    }

    public static void launchTraffic(Activity context, double longitude, double latitude) {
        launch(context, longitude, latitude, context.getResources().getString(R.string.highway_condition), "", "", MAP_TYPE_TRAFFIC);
    }

    public static void launch(Activity context, double longitude, double latitude, String targetName, String startName, String endName, int mapType) {
        Intent intent = new Intent(context, MapActivity.class);
        intent.putExtra(TARGET_LONGITUDE, longitude);
        intent.putExtra(TARGET_LATITUDE, latitude);
        intent.putExtra(TARGET_NAME, targetName);
        intent.putExtra(ROUTE_START, startName);
        intent.putExtra(ROUTE_END, endName);
        intent.putExtra(MAP_TYPE, mapType);
        context.startActivity(intent);
    }

    private boolean trafficIsEnabled() {
        if (mMapType == MAP_TYPE_TRAFFIC || mMapType == MAP_TYPE_ROUTE) {
            return true;
        }
        return false;
    }

    private void initMapView() {
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        int zoomLevel = 18;
        if (trafficIsEnabled()) {
            //开启交通图
            mBaiduMap.setTrafficEnabled(true);
            zoomLevel = 14;
        }

        setTitle(mTargetName);

        LatLng point = new LatLng(mTargetLatitude, mTargetLongitude);
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.ic_current_location);

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);

        MapStatus mMapStatus = new MapStatus.Builder()
                .target(point)
                .zoom(zoomLevel)
                .build();
        mBaiduMap.addOverlay(option);
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    protected void onDestroy() {
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        super.onDestroy();
    }

    // 定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {

            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {

            return null;
        }
    }
}
